package ynu.sxp.demo.common;

import lombok.SneakyThrows;
import lombok.extern.apachecommons.CommonsLog;

import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyPair;
import java.security.KeyPairGenerator;

@CommonsLog
public class RsaKeyTool {

    public static KeyPair getOrCreateKeyPair(String filename) throws Exception {
        if (Paths.get(filename).toFile().exists()) {
            return loadKeyPairFromFile(filename);
        }else {
            var keyPair = generateRSAKeyPair();
            var filefullPath = saveKeyPairToFile(keyPair, filename);
            log.info("密钥对已保存到文件: " + filefullPath);
            return keyPair;
        }
    }

    // 生成 RSA 密钥对
    @SneakyThrows
    public static KeyPair generateRSAKeyPair() {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(2048);
        return keyPairGenerator.generateKeyPair();
    }

    // 将密钥对保存到文件
    public static Path saveKeyPairToFile(KeyPair keyPair, String filename) throws Exception {
        var fileStream = new FileOutputStream(filename);
        try (var objectOutputStream = new ObjectOutputStream(fileStream)) {
            objectOutputStream.writeObject(keyPair);
            return Paths.get(filename).toAbsolutePath();
        }catch (Exception e){
            log.error("保存密钥对到文件失败", e);
            throw e;
        }
    }

    // 从文件中加载密钥对
    public static KeyPair loadKeyPairFromFile(String filename) throws Exception {
        try (var objectInputStream = new ObjectInputStream(new FileInputStream(filename))) {
            return (KeyPair) objectInputStream.readObject();
        }
    }
}
